﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace LJ.WebApi.UnifyResult.Mvc.Filters;

/// <summary>
/// 数据验证拦截器
/// </summary>
public sealed class UnifyValidationFilter : IAsyncActionFilter, IOrderedFilter
{
    /// <summary>
    /// 排序属性
    /// </summary>
    public int Order => -1000;

    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        // 如果验证通过，跳过后面的动作
        if (!context.ModelState.IsValid)
        {
            // 获取失败的验证信息列表
            var error = context.ModelState
                .Where(s => s.Value != null && s.Value.ValidationState == ModelValidationState.Invalid)
                .SelectMany(s => s.Value!.Errors.ToList())
                .Select(e => e)
                .First();

            var result = new WebApiResult<object>
            {
                Succeeded = false,
                StatusCode = StatusCodes.Status400BadRequest,
                Message = error.ErrorMessage
            };

            context.Result = new ObjectResult(result);
            context.HttpContext.Response.StatusCode = StatusCodes.Status200OK;
        }
        else
        {
            await next();
        }

    }
}